package org.jflame.commons.json.jackson;

import java.lang.annotation.Annotation;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector;

/**
 * 自定义注解内省器
 * 
 * @author charles.zhang
 */
@SuppressWarnings("rawtypes")
public class CustomAnnotationIntrospector extends NopAnnotationIntrospector {

    private static final long serialVersionUID = 1L;

    private Class<? extends Annotation> customAnnotation;

    private Class<? extends JsonSerializer> serializerClass;
    private Class<? extends JsonDeserializer> deserializerClass;

    public CustomAnnotationIntrospector(Class<? extends Annotation> customAnnotation,
            Class<? extends JsonSerializer> serializerClass) {
        this(customAnnotation, serializerClass, null);
    }

    public CustomAnnotationIntrospector(Class<? extends Annotation> customAnnotation,
            Class<? extends JsonSerializer> serializerClass, Class<? extends JsonDeserializer> deserializerClass) {
        this.customAnnotation = customAnnotation;
        if (serializerClass == null && deserializerClass == null) {
            throw new IllegalArgumentException("serializerClass or deserializerClass must not be null");
        }
        this.serializerClass = serializerClass;
        this.deserializerClass = deserializerClass;
    }

    @Override
    public Object findSerializer(Annotated am) {
        if (serializerClass != null && am.hasAnnotation(customAnnotation)) {
            return serializerClass;
        }
        return super.findSerializer(am);
    }

    @Override
    public Object findDeserializer(Annotated am) {
        if (deserializerClass != null && am.hasAnnotation(customAnnotation)) {
            return deserializerClass;
        }
        return super.findDeserializer(am);
    }

}
